package com.studyroom.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.studyroom.constant.RedisConstantsKey;
import com.studyroom.mapper.UserMapper;
import com.studyroom.pojo.User;
import com.studyroom.service.user.UserService;
import com.studyroom.util.JwtTokenUtils;
import com.studyroom.util.ResponseEntity;
import com.studyroom.util.ResponseUtils;
import com.studyroom.vo.admin.LoginParamVo;
import com.studyroom.vo.admin.UserVo;
import io.lettuce.core.api.sync.RedisCommands;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wuhongbin
 * @version 1.0.0
 * @ClassName UserServiceImpl.java
 * @createTime 2021年11月02日 10:21:00
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final RedisCommands<String,String> redisCommands;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, @Qualifier("syncCommand") RedisCommands<String,String> redisCommands) {
        this.userMapper = userMapper;
        this.redisCommands = redisCommands;
    }

    @Override
    public int registerUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public User selectUserByPhone(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public Boolean isUserExist(String phone) {
        User user = selectUserByPhone(phone);
        return user == null ? false : true;
    }

    @Override
    public ResponseEntity<?> loginByCaptcha(LoginParamVo paramVo) {
        String captcha = paramVo.getCaptcha();
        String phone = paramVo.getPhone();
        User user = selectUserByPhone(phone);
        if (ObjectUtils.isEmpty(user)){
            User mUser = User.builder()
                    .phone(phone).build();
            userMapper.insert(mUser);
        }
        String key = String.format(RedisConstantsKey.SMS_CODE_STRING, phone);
        if (!captcha.equals(redisCommands.get(key)) || redisCommands.get(key) == null){
            return ResponseUtils.fail("验证码错误");
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("phone",phone);
        map.put("captcha",captcha);
        String token = JwtTokenUtils.generateToken(map);
        UserVo userVo = UserVo.builder()
                .username(user.getUsername())
                .phone(user.getPhone())
                .token(token)
                .avatar(user.getImageUrl())
                .isAdmin(user.getAdmin() == 0).build();
        return ResponseUtils.success(userVo);
    }


}
